package com.objk.admin.security.hander;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.obj.commpont.common.vo.ServerResponse;
import com.objk.admin.security.constans.LoginResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.objk.admin.security.constans.LoginResponseCode.*;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        if (exception instanceof UsernameNotFoundException) {
            response.getWriter().write(objectMapper.writeValueAsString(ServerResponse.createByResponseCode(USERNAME_NOT_FOUND)));
        } else if (exception instanceof BadCredentialsException) {
            response.getWriter().write(objectMapper.writeValueAsString(ServerResponse.createByResponseCode(PASSWORD_ERROR)));
        } else {
            response.getWriter().write(objectMapper.writeValueAsString(ServerResponse.createByResponseCode(PASSWORD_ERROR)));
        }
    }
}
